<template>
  <div id="fleetView" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">车队视图</BreadcrumbItem>
				<BreadcrumbItem to="/fleet/view">车队视图</BreadcrumbItem>
			</Breadcrumb>
			<div class="btns">
				<ButtonGroup>
	        <Button type="text" @click="gotoDetail"><span>更多历史数据</span> <i class="fa fa-angle-double-right"></i></Button>
	    	</ButtonGroup>
			</div>
		</div>
    <TableSearch>
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <FormItem label="车队">
              <Select v-model="orgIds" placeholder="请选择车队">
                <OrgTreeOption></OrgTreeOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search" long>查询</Button>
		</TableSearch>

    <div class="main">
      <Row :gutter="16">
        <Col :md="6" class="chart-col">
          <div class="block">
            <div class="block-body">
              <div class="dash-board-box">
                <div id="dashBoardChart" style="width:100%;height:250px;"></div>
                <div class="dash-board-foot">
                  <div class="rank">
                    <span>车队排名</span>
                    <span class="rank-num">{{data.companyRanking}}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Col>
        <Col :md="18">
          <Row>
            <Col :md="17" class="col-no-padding" style="padding-left:0;">
              <Card dis-hover>
                <div class="info-grid">
                  <div class="grid-item">
                    <Row>
                      <Col :md="5" :offset="1">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{((data.mileage||0)/1000).toFixed(0)}}</span>
                            <span class="unit">公里</span>
                          </div>
                          <div class="data-name">行驶里程累计</div>
                        </div>
                      </Col>
                      <Col :md="5">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{durationHours}}</span>
                            <span class="unit">小时</span>
                          </div>
                          <div class="data-name">行驶时长累计</div>
                        </div>
                      </Col>
                      <Col :md="5" :offset="2">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.totalWzTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">违章累计</div>
                        </div>
                      </Col>
                      <Col :md="5">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.accidentTtimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">事故累计</div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                  <div class="grid-item">
                    <Row>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.overspeedTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">超速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.accelerateTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急加速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.decelerateTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急减速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.sharpTurnTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急转弯累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.callPhoneTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">行驶中拨打手机</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.lookPhoneTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">行驶中看手机</div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                </div>
              </Card>
            </Col>
            <Col :md="7" style="padding-right:0;">
              <Card dis-hover>
                <div class="team-info">
                  <div class="info-header"><h2>{{data.orgName}}</h2></div>
                  <ul class="star">
                    <li v-for="v in 5" :class="`${calcStar(v,data.securityIndex===null?100:data.securityIndex)}`" :key="`star-li-${v}`"></li>
                  </ul>
                  <div class="info">
                    <span>驾驶员 {{data.totalDriver||0}} 人</span>
                    <span>车辆  {{data.totalVehicle||0}} 辆</span>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>

          <div class="search-box">
            <Button :class="{'ivu-btn-primary':twelveMonthActive}" @click="twelveMonthClick">最近12个月</Button>
            <DatePicker v-model="searchYear" type="year" :options="yearOption" :editable="false" :clearable="false" placement="bottom-end" transfer placeholder="选择年" style="width:120px;"></DatePicker>
          </div>
        </Col>
      </Row>

      <div class="sub-content">
        <Row :gutter="16">
          <Col :md="24">
            <Card dis-hover>
              <div slot="title">行驶里程/时长</div>
              <div id="driveChart" style="width:100%;height:220px;"></div>
            </Card>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :md="18">
            <Card dis-hover>
              <div slot="title">不良驾驶行为</div>
              <div id="driveBehaviorChart" style="width:100%;height:220px;"></div>
            </Card>
          </Col>
          <Col :md="6">
            <Card dis-hover>
              <div slot="title">百公里均值</div>
              <div class="list-info">
                <div class="list-item">
                  <div class="item-name">超速</div>
                  <div class="item-number"><span class="number">{{data.bglOverspeedTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
                <div class="list-item">
                  <div class="item-name">疲劳驾驶</div>
                  <div class="item-number"><span class="number">{{data.bglFatigueDrivingTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
                <div class="list-item">
                  <div class="item-name">急加速</div>
                  <div class="item-number"><span class="number">{{data.bglAccelerateTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
                <div class="list-item">
                  <div class="item-name">急减速</div>
                  <div class="item-number"><span class="number">{{data.bglDecelerateTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
                <div class="list-item">
                  <div class="item-name">急转弯</div>
                  <div class="item-number"><span class="number">{{data.bglSharpTurnTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :md="18">
            <Card dis-hover>
              <div slot="title">不良操作行为</div>
              <div id="operBehaviorChart" style="width:100%;height:220px;"></div>
            </Card>
          </Col>
          <Col :md="6">
            <Card dis-hover>
              <div slot="title">百公里均值</div>
              <div class="list-info">
                <div class="list-item">
                  <div class="item-name">行驶中拨打电话</div>
                  <div class="item-number"><span class="number">{{data.callPhoneTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
                <div class="list-item">
                  <div class="item-name">行驶中看手机</div>
                  <div class="item-number"><span class="number">{{data.lookPhoneTimes|isNull}}</span><span class="unit">次</span></div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :md="18">
            <Card dis-hover>
              <div slot="title">情绪</div>
              <div id="moodChart" style="width:100%;height:220px;"></div>
            </Card>
          </Col>
          <Col :md="6">
            <Card dis-hover>
              <div slot="title">均值</div>
              <div class="list-info">
                <div class="list-item">
                  <div class="item-name">情绪指数均值</div>
                  <div class="item-number"><span class="number">{{data.avgSentimentIndexScore|isNull}}</span><span class="unit">分</span></div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :md="18">
            <Card dis-hover>
              <div slot="title">生活习惯</div>
              <div slot="extra" class="habits-desc">
                <span>过度(睡眠大于8小时)</span>
                <span>优(睡眠7~8小时)</span>
                <span>良(睡眠6~7小时)</span>
                <span>一般(睡眠5~6小时)</span>
                <span>较差(睡眠4~5小时)</span>
                <span>差(睡眠小于4小时)</span>
              </div>
              <div id="habitsChart" style="width:100%;height:220px;"></div>
            </Card>
          </Col>
          <Col :md="6">
            <Card dis-hover>
              <div slot="title">均值</div>
              <div class="list-info">
                <div class="list-item">
                  <div class="item-name">睡眠时长均值</div>
                  <div class="item-number"><span class="number">{{time(data.avgSleepDuration*3600,1,1)}}</span></div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
        <Spin size="large" fix v-if="isLoading"></Spin>
      </div>
    </div>


  </div>
</template>
<style lang="less" src="@/assets/styles/fleet/fleet-view.less"></style>

<script>
	import {mapState,mapActions} from 'vuex'
  import moment from 'moment'
  import unit   from '@/util/unit'
  import EChart from '@/plugin/EChart'

  export default {
    mounted(){
      this.search();
    },
    destroyed(){
      this.dashboardChart && this.dashboardChart.dispose();
      this.driveChart && this.driveChart.dispose();
      this.driveBehaviorChart && this.driveBehaviorChart.dispose();
      this.operBehaviorChart && this.operBehaviorChart.dispose();
      this.moodChart && this.moodChart.dispose();
      this.habitsChart && this.habitsChart.dispose();
    },
    data(){
      return {
        orgIds:'',
        twelveMonthActive:true,
        searchYear:'',
        isLoading:false,

        dashboardChart:null,
        driveChart:null,
        driveBehaviorChart:null,
        operBehaviorChart:null,
        moodChart:null,
        habitsChart:null,

        yearOption:{
          disabledDate:(d)=>{
            return d > moment().toDate();
          }
        }
      };
    },
    watch:{
      searchYear(v){
        if (v) {
          this.twelveMonthActive = false;
          this.update();
        }
      }
    },
    computed:{
      ...mapState('base',['userinfo']),
      ...mapState('fleet/fleetView',['data']),
      durationHours(){
        let h = moment.duration(this.data.duration||0,'s').asHours();
        return Math.floor(h);
      }
    },
    methods:{
      moment,
      time:unit.time,mileage:unit.mileage,
      ...mapActions('fleet/fleetView',['loadFleetView']),
      async search(){
        let query = {orgIds:this.orgIds};
        if (this.searchYear) query.year = moment(this.searchYear).format('YYYY');
        this.isLoading = true;
        await this.loadFleetView(query);
        this.isLoading = false;
        this.initData();
        if (!this.orgIds) this.orgIds = this.data.orgId;
      },
      async update(){
        let query = {orgIds:this.orgIds};
        if (this.searchYear) query.year = moment(this.searchYear).format('YYYY');
        await this.loadFleetView(query);
        this.updateData();
      },
      twelveMonthClick(){
        this.twelveMonthActive = true;
        this.searchYear = '';
        this.update();
      },
      // 计算星星
      calcStar(v,si){
        let sc = si / 20;
        if (v < sc) return 'all';
        if (v > sc && v - sc < 0.5) return 'hal';
        return '';
      },
      initData(){
        this.createDashboardChart();
        this.updateData();
      },
      updateData(){
        this.createDriveChart();
        this.createDriveBehaviorChart();
        this.createOperBehaviorChart();
        this.createMoodChart();
        this.createHabitsChart();
      },
      createDashboardChart(){
        this.dashboardChart = new EChart('dashBoardChart',{
          toolbox:{show:false},
          tooltip:{formatter:"{a} <br/>{b}：{c}"},
          series:[
            {
              name: this.data.orgName||'--',type: 'gauge',radius:'90%',
              detail: {formatter:'{value}',fontSize:48},
              data: [{value: this.data.securityIndex===null?100:this.data.securityIndex, name: '综合安全指数'}],
              title:{fontSize:14,offsetCenter:[0,'70%']},
              axisLine:{lineStyle:{color:[[0.3, '#fd666d'], [0.7, '#37a2da'], [1, '#3be4e4']]}}
            }
          ]
        });
      },
      createDriveChart(){
        let xAxis = this.data.mileageList.map(o => o.date);
        let mdata = this.data.mileageList.map(o => o.mileage/1000);
        let ddata = this.data.mileageList.map(o => o.duration/60/60);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#00B050','#FFB163'],
          grid:{x:50,y:40,right:50,bottom:40},
          tooltip: {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                let data = o.seriesName.indexOf('里程') >= 0 ? this.mileage(o.data*1000) : this.time(o.data*60,2,2);
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${data}`;
              });
              return tooltiphtml;
            }
          },
          legend: {data:['行驶里程','行驶时长'],right:0},
          xAxis:[{type: 'category',axisLabel:{interval:0},data: xAxis}],
          yAxis:[
            {type:'value',splitNumber:7,min:0,axisPointer:{label:{formatter:'{value}公里'}}},
            {type:'value',splitNumber:7,min:0,axisPointer:{label:{formatter:'{value}小时'}}}
          ],
          series:[
            {name:'行驶里程',type:'bar',barWidth:30,yAxisIndex: 0,data:mdata},
            {name:'行驶时长',type:'line',smooth:true,yAxisIndex: 1,data:ddata}
          ]
        };
        if (this.driveChart){
          this.driveChart.setOption(option);
        } else {
          this.driveChart = new EChart('driveChart',option);
        }
      },
      createDriveBehaviorChart(){
        let xAxis = this.data.badDriveingList.map(o => o.date);
        let overspeedTimes = this.data.badDriveingList.map(o => o.overspeedTimes);// 超速
        let fatigueDrivingTimes = this.data.badDriveingList.map(o => o.fatigueDrivingTimes);// 疲劳驾驶
        let accelerateTimes = this.data.badDriveingList.map(o => o.accelerateTimes);//急加速
        let decelerateTimes = this.data.badDriveingList.map(o => o.decelerateTimes);// 急减速
        let sharpTurnTimes = this.data.badDriveingList.map(o => o.sharpTurnTimes);// 急转弯
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#FFC000','#FF6600','#376092','#9E6A93','#4BACC6'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip:{
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}次`;
              });
              return tooltiphtml;
            }
          },
          legend: {data:['超速','疲劳驾驶','急加速','急减速','急转弯'],right:0},
          xAxis:[{type: 'category',axisLabel:{interval:0},data: xAxis}],
          yAxis:[{type:'value',splitNumber:7,min:0}],
          series:[
            {name: '超速',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: overspeedTimes},
            {name: '疲劳驾驶',type: 'bar',stack: 'DriveBehavior',data: fatigueDrivingTimes},
            {name: '急加速',type: 'bar',stack: 'DriveBehavior',data: accelerateTimes},
            {name: '急减速',type: 'bar',stack: 'DriveBehavior',data: decelerateTimes},
            {name: '急转弯',type: 'bar',stack: 'DriveBehavior',data: sharpTurnTimes},
          ]
        };
        if (this.driveBehaviorChart){
          this.driveBehaviorChart.setOption(option);
        } else {
          this.driveBehaviorChart = new EChart('driveBehaviorChart',option);
        }
      },
      createOperBehaviorChart(){
        let xAxis = this.data.badOperationList.map(o => o.date);
        let callPhoneTimes = this.data.badOperationList.map(o => o.callPhoneTimes||0);
        let lookPhoneTimes = this.data.badOperationList.map(o => o.lookPhoneTimes||0);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#31859C','#93CDDD'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip:{
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}次`;
              });
              return tooltiphtml;
            }
          },
          legend: {data:['行驶中拨打电话','行驶中看手机'],right:0},
          xAxis:[{type: 'category',axisLabel:{interval:0},data: xAxis}],
          yAxis:[{type:'value',splitNumber:7,min:0}],
          series:[
            {name: '行驶中拨打电话',type: 'bar',stack: 'OperBehavior',barWidth:30,data: callPhoneTimes},
            {name: '行驶中看手机',type: 'bar',stack: 'OperBehavior',barWidth:30,data: lookPhoneTimes}
          ]
        };
        if (this.operBehaviorChart){
          this.operBehaviorChart.setOption(option);
        } else {
          this.operBehaviorChart = new EChart('operBehaviorChart',option);
        }
      },
      createMoodChart(){
        let xAxis = this.data.emotionList.map(o => o.date);
        let series = this.data.emotionList.map(o => o.sentimentIndexScore);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#376092'],
          grid:{x:30,y:10,right:0,bottom:40},
          tooltip:{
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}天`;
              });
              return tooltiphtml;
            }
          },
          xAxis:[{type: 'category',axisLabel:{interval:0},data: xAxis}],
          yAxis:[{type:'value',splitNumber:7,min:0}],
          series:[
            {name:'情绪指数',type:'line',smooth:true,data:series}
          ]
        };
        if (this.moodChart){
          this.moodChart.setOption(option);
        } else {
          this.moodChart = new EChart('moodChart',option);
        }
      },
      createHabitsChart(){
        let xAxis = this.data.habitsList.map(o => o.date);
        let series = this.data.habitsList.map(o => o.sleepDuration);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#376092'],
          grid:{x:30,y:10,right:0,bottom:40},
          tooltip:{
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}小时`;
              });
              return tooltiphtml;
            }
          },
          xAxis:[{type: 'category',axisLabel:{interval:0},data: xAxis}],
          yAxis:[{type:'value',splitNumber:7,min:0}],
          series:[
            {name:'睡眠时长',type:'line',smooth:true,data:series}
          ]
        };
        if (this.habitsChart){
          this.habitsChart.setOption(option);
        } else {
          this.habitsChart = new EChart('habitsChart',option);
        }
      },
      gotoDetail(){
        let detail = {name:'fleetStatistics',query:{orgIds:this.orgIds}};
        this.$router.push(detail);
      }
    },
    filters:{
      isNull(v){
        return v === null ? '-' : v;
      }
    }
  }
</script>
